import '../assets/css/index.scss';

import React, { useState } from 'react';

import {
  Button,
  Image,
  Spin,
  Table,
} from 'antd';

import {
  useAppQuery,
  useAuthenticatedFetch,
} from '../hooks';

export const ProductVariants = (props) => {
  const emptyToastProps = { content: null };
  const [isLoading, setIsLoading] = useState(false);
  const [isError, setIsError] = useState(false);
  const [product, setProduct] = useState(null);
  const [open, setOpen] = useState(false);

  const [toastProps, setToastProps] = useState(emptyToastProps);
  const fetch = useAuthenticatedFetch();
  function aiImageAction(_product){
    setProduct(_product)
    setOpen(true);
  }
  const columns = [
    {
      title: 'Propery',
      dataIndex: 'title',
      key: 'title',
      render: (text, record) => (
        <>
          <span class="btn">{text}&nbsp;&nbsp;&nbsp;&nbsp;</span>
          {record.image_id  ?
  
            <Image className='btn'  src={props.imageMap[record.image_id]} alt={`Image of ${text}`} width={40}
              height={40} />
            :
            <Image className='btn'
              width={40}
              height={40}
              src="error"
              fallback=""
            />}
  
  
  
        </>
      ),
    },
 
    {
      title: 'sku',
      dataIndex: 'sku',
      key: 'sku',
    },
    {
      title: 'Action',
      dataIndex: 'status',
      key: 'status',
      render: (text, record) => (
         (<Button type="primary" class="btn" onClick={()=>{aiImageAction(record)}}>
          AI Imager
        </Button>
        )
        )
    },
    
  ];
  const {
    data
  } = useAppQuery({
    url: "/api/products",
    reactQueryOptions: {
      onSuccess: () => {
        setIsLoading(false);
      },
      onerror: () => {
        setIsError(true);
      }
    },
  });
  if (isLoading) return <Spin />;
  if (isError) return <p>Error :(</p>;

  return (
    <>
  
        <Table
    style={{width:"100%"}}
      columns={columns}
      dataSource={props.variants.map((node) => ({
        key: node.id,
        title: node.title,
        image_id:node.image_id,
        image: props.imageMap[node.image_id],
        sku: node.sku,
        product_id: node.product_id

      }))}
    />
     
    </>

  );
};
